package online.mjchow.fic.controller.interceptor;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import online.mjchow.fic.util.ApiResult;
import online.mjchow.fic.util.ApiStatus;
import online.mjchow.fic.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Created by mjchow on 17-12-4.
 */
public class AdminIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(request.getRequestURI().contains("/export")) {
            return true;
        }
        String token = request.getHeader("access_token");
        Integer uid = null;
        if(token != null && token.length() > 0) {
            Claims claims = JWTUtil.parseJWT(token);
            if(claims != null) {
                uid = Integer.parseInt((String) claims.get("id"));
                request.setAttribute("adminId", uid);
                return true;
            }
        }
        ApiResult result = new ApiResult(ApiStatus.NOT_LOGIN);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
        httpServletResponse.getWriter().flush();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
